package com.zk.algorithm.backtracking;

import com.zk.algorithm.annotation.CrackingTheCodingInterview6;
import com.zk.algorithm.annotation.LeetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.com/problems/permutations/
 * https://leetcode.com/problems/permutations/discuss/18239/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partioning)
 *
 * @author zk
 */
@LeetCode
@CrackingTheCodingInterview6("8.7")
public class Permutations {

    // nums 每个数字都不同
    // 全排列
    //
    // [1]
    //   [1,1] X
    //     [1,1,1] X
    //     [1,1,2] X
    //     [1,1,3] X
    //   [1,2]
    //     [1,2,1] X
    //     [1,2,2] X
    //     [1,2,3]
    //   [1,3]
    //     [1,3,1] X
    //     [1,3,2]
    //     [1,3,3] X
    // [2]
    //   [2,1]
    //     [2,1,1] X
    //     [2,1,2] X
    //     [2,1,3]
    //   [2,2] X
    //     [2,2,1] X
    //     [2,2,2] X
    //     [2,2,3] X
    //   [2,3]
    //     [2,3,1]
    //     [2,3,2] X
    //     [2,3,3] X
    // [3]
    //   [3,1]
    //     [3,1,1] X
    //     [3,1,2]
    //     [3,1,3] X
    //   [3,2]
    //     [3,2,1]
    //     [3,2,2] X
    //     [3,2,3] X
    //   [3,3] X
    //     [3,3,1] X
    //     [3,3,2] X
    //     [3,3,3] X
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        backtrack(list, new ArrayList<>(), nums);
        return list;
    }

    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] nums) {
        if (tempList.size() == nums.length) {
            list.add(new ArrayList<>(tempList));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (tempList.contains(nums[i]))
                    continue; // element already exists, skip

                // ========================
                // 末尾添加
                // ========================
                tempList.add(nums[i]);
                // ========================
                // 回溯
                // ========================
                backtrack(list, tempList, nums);
                // ========================
                // 末尾去除
                // ========================
                tempList.remove(tempList.size() - 1);
            }
        }
    }

}